package com.example.mq2.mqserver.datacenter;

import com.example.mq2.common.Mq2Exception;
import com.example.mq2.mqserver.core.Binding;
import com.example.mq2.mqserver.core.Exchange;
import com.example.mq2.mqserver.core.MSGQueue;
import com.example.mq2.mqserver.core.Message;
import sun.misc.resources.Messages_es;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/*
* 使用这个类来管理硬盘上的所有数据
* 1.数据库：交换机，队列，绑定
* 2. 数据文件：消息*/
public class DiskDataCenter {
    // 这个实例用来管理数据库中的数据
    private DataBaseManager dataBaseManager = new DataBaseManager();
    // 这个实例用来管理数据文件的数据
    private MessageFileManager messageFileManager = new MessageFileManager();

    public void init() {
        dataBaseManager.init();
        messageFileManager.init();
    }

    // 封装交换机操作
    public void insertExchange(Exchange exchange) {
        dataBaseManager.insertExchange(exchange);
    }
    public void deleteExchange(String exchangeName) {
        dataBaseManager.deleteExchange(exchangeName);
    }
    public List<Exchange> selectAllExchange() {
        return dataBaseManager.selectAllExchanges();
    }

    // 封装队列操作
    public void insertQueue(MSGQueue queue) {
        dataBaseManager.insertQueue(queue);
    }
    public void deleteQueue(String queueName) {
        dataBaseManager.deleteQueue(queueName);
    }
    public List<MSGQueue> selectAllQueue() {
        return dataBaseManager.selectAllQueues();
    }

    // 封装绑定操作
    public void insertBinding(Binding binding) {
        dataBaseManager.insertBinding(binding);
    }
    public void deleteBinding(Binding binding) {
        dataBaseManager.deleteBinding(binding);
    }
    public List<Binding> selectAllBinding() {
        return dataBaseManager.selectAllBindings();
    }

    // 封装消息的操作
    public void sendMessage(MSGQueue queue, Message message) throws Mq2Exception, IOException {
        messageFileManager.sendMessage(queue, message);
    }
    public void deleteMessage(MSGQueue queue, Message message) throws IOException, ClassNotFoundException, Mq2Exception {
        messageFileManager.deleteMessage(queue, message);
        // 此时删除消息不仅仅是删除，还要考虑多了一个无效的消息之后是否 要进行GC
        if (messageFileManager.checkGC(queue.getName())) {
            messageFileManager.gc(queue);
        }
    }
    public LinkedList<Message> loadAllMessageFromQueue(String queueName) throws Mq2Exception, IOException, ClassNotFoundException {
         return messageFileManager.loadAllMessageFromQueue(queueName);
    }
}
